<?php

define( "ERROR", 1 );
define( "WARNING", 2 );
define( "INFO", 3 );

define( "LOG_UNKNOWN_MESSAGE", 0 );
define( "LOG_INFO_RESERVATION_DONE", 1 );
define( "LOG_INFO_RESERVATION_CANCELED", 2 );
define( "LOG_INFO_USER_REGISTERED", 3 );
define( "LOG_INFO_PASSWORD_CHANGED", 4 );
define( "LOG_INFO_USER_LOGGED", 5 );
define( "LOG_INFO_USER_LOGOUT", 6 );

function clearHtmlFromMessage( $message )
{
    $outStr = strip_tags( $message );
    $outStr = trim( $outStr, "\n" );
    $outStr = trim( $outStr, "\r" );
    return $outStr;
}

function numberStr( $number )
{
    if ($number < 10)
        return sprintf( "0%d", $number );
        
    return sprintf( "%d", $number );
}

function logFunction( $type, $message, $messageNumber )
{
    
    $message = clearHtmlFromMessage( $message );
    $logPath = $_SERVER['DOCUMENT_ROOT'] . "/log.log";
    $fh = fopen( $logPath, 'a' );
    if (! $fh)
        return;
     
    $stringData = "";   
    switch ($type)
    {
    case ERROR:
        $stringData = "[ERROR]";
        break;
       
    case WARNING:
        $stringData = "[WARNING]";
        break;
       
    case INFO:
        $stringData = "[INFO]";
        break;
        
    default:
      break;
    }
    
    $currentDateTime = getDate();
    $dateStr = sprintf( "[%s.%s.%d %s:%s:%s]", 
        numberStr( $currentDateTime['mday'] ), 
        numberStr( $currentDateTime['mon'] ),
        $currentDateTime['year'], 
        numberStr( $currentDateTime['hours'] ),
        numberStr( $currentDateTime['minutes'] ), 
        numberStr( $currentDateTime['seconds'] ) );
    $stringData .= $dateStr . "[" . $message . "]";
    if ($messageNumber > 0)
        $stringData .= "[ " . $messageNumber . " ]";
    
    $stringData .= "\n";
    if (flock( $fh, LOCK_EX )) 
    {
        fwrite( $fh, $stringData );
        fclose( $fh );
        return;
    }

    fclose( $fh );
}

function logError( $message, $messageNumber = 0 )
{
    logFunction( ERROR, $message, $messageNumber );
}

function logWarning( $message, $messageNumber = 0 )
{
    logFunction( WARNING, $message, $messageNumber );
}

function logInfo( $message, $messageNumber = 0 )
{
    logFunction( INFO, $message, $messageNumber );
}

?>
